package com.peng.config;

import com.peng.mapper.UserMapper;
import com.peng.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class SecurityLoginUser implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectUserByUserName(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        String[] str = new String[]{userMapper.selectRoleById(user.getRoleId()).getName()};
        System.out.println("用户" + user.getUsername() + "权限集合:" + Arrays.toString(str));
        org.springframework.security.core.userdetails.User result =
                new org.springframework.security.core.userdetails.User(s, user.getPassword(), AuthorityUtils.createAuthorityList(str));
        return result;
    }
}
